package com.liyongjian.xhban.api;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liyongjian.xhban.dal.AccountGroupDetailRepository;
import com.liyongjian.xhban.dal.AccountGroupFamilyRepository;
import com.liyongjian.xhban.dal.AccountGroupRepository;
import com.liyongjian.xhban.dal.BlogCommentRepository;
import com.liyongjian.xhban.dal.BlogMediaRepository;
import com.liyongjian.xhban.dal.BlogRepository;
import com.liyongjian.xhban.dal.GroupRepository;
import com.liyongjian.xhban.dal.UserRepository;
import com.liyongjian.xhban.dto.AjaxResponse;
import com.liyongjian.xhban.dto.SessionUser;
import com.liyongjian.xhban.model.AccountGroupDetail;
import com.liyongjian.xhban.model.AccountGroupFamily;
import com.liyongjian.xhban.model.Blog;
import com.liyongjian.xhban.model.BlogComment;
import com.liyongjian.xhban.model.Group;
import com.liyongjian.xhban.model.User;
import com.liyongjian.xhban.model.emumm.BlogType;
import com.liyongjian.xhban.model.emumm.LiveDieState;
import com.liyongjian.xhban.model.emumm.VerifyState;
import com.liyongjian.xhban.utils.MapUtils;


@Controller
@RequestMapping("/api/blog")
public class BlogController extends BaseController {

    @Autowired
    private BlogRepository blogRepository;
    @Autowired
    private BlogMediaRepository blogMediaRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private AccountGroupDetailRepository accountGroupDetailRepository;
    @Autowired
    private GroupRepository groupRepository;
    @Autowired
    private AccountGroupFamilyRepository accountGroupFamilyRepository;
    @Autowired
    private BlogCommentRepository blogCommentRepository;

    @ResponseBody
    @RequestMapping(path = "index", method = RequestMethod.GET)
    public AjaxResponse login(HttpServletRequest request, String token, String nickName,
            String avatarUrl, HttpServletResponse response,
            @PageableDefault(sort = {"id"}, direction = Direction.DESC) Pageable pageable)
                    throws Exception {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getCurrentUser(token);
        Page<Blog> page = blogRepository.pageByUserId(su.getId(), "," + su.getId() + ",", pageable);
        return ajax.setObj(page.map(new Converter<Blog, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(Blog source) {
                Map<String, Object> map = MapUtils.convert(source);
                if (source.type == BlogType.HH) {
                    AccountGroupDetail agd = accountGroupDetailRepository.findByBlogId(source.id);
                    map.put("agdState", agd.state);
                    Group group = groupRepository.findOne(agd.groupId);
                    map.put("groupId", group.id);
                    map.put("groupName", group.name);
                    map.put("isSealed", group.isSealed);
                } else if (source.type == BlogType.JT) {
                    AccountGroupFamily agf = accountGroupFamilyRepository.findByBlogId(source.id);
                    Group group = groupRepository.findOne(agf.groupId);
                    map.put("groupId", group.id);
                    map.put("groupName", group.name);
                    map.put("isSealed", group.isSealed);
                }

                User user = userRepository.findOne(source.userId);
                map.put("nickName", user.nickName);
                map.put("photo", user.photo);
                map.put("urls", blogMediaRepository.findUrlByBlogId(source.id));

                Page<BlogComment> page = blogCommentRepository.findByBlogIdAndState(source.id,
                        LiveDieState.LIVE, new PageRequest(0, 2));
                map.put("plList", page.map(new Converter<BlogComment, Map<String, Object>>() {

                    public Map<String, Object> convert(BlogComment source) {
                        Map<String, Object> map = MapUtils.convert(source);
                        User user = userRepository.findOne(source.userId);
                        map.put("nickName", user.nickName);
                        map.put("photo", user.photo);
                        return map;
                    }

                }).getContent());
                return map;
            }

        }));
    }



    @ResponseBody
    @RequestMapping(path = "detail", method = RequestMethod.GET)
    public AjaxResponse detail(HttpServletRequest request, String token, Long id,
            HttpServletResponse response,
            @PageableDefault(sort = {"id"}, direction = Direction.DESC) Pageable pageable)
                    throws Exception {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getCurrentUser(token);
        Blog blog = blogRepository.findOne(id);
        Map<String, Object> map = MapUtils.convert(blog);
        if (blog.type == BlogType.HH) {
            AccountGroupDetail agd = accountGroupDetailRepository.findByBlogId(blog.id);
            map.put("agdState", agd.state);
            Group group = groupRepository.findOne(agd.groupId);
            map.put("updUserId", group.updUserId);
            map.put("groupId", group.id);
            map.put("groupName", group.name);
            map.put("isSealed", group.isSealed);
        } else if (blog.type == BlogType.JT) {
            AccountGroupFamily agf = accountGroupFamilyRepository.findByBlogId(blog.id);
            Group group = groupRepository.findOne(agf.groupId);
            map.put("groupId", group.id);
            map.put("groupName", group.name);
            map.put("isSealed", group.isSealed);
        }

        User user = userRepository.findOne(blog.userId);
        map.put("nickName", user.nickName);
        map.put("photo", user.photo);
        map.put("urls", blogMediaRepository.findUrlByBlogId(blog.id));

        return ajax.setObj(map);
    }


    @ResponseBody
    @RequestMapping(path = "comment_list", method = RequestMethod.GET)
    public AjaxResponse comment_list(HttpServletRequest request, String token, Long id,
            HttpServletResponse response,
            @PageableDefault(sort = {"id"}, direction = Direction.DESC) Pageable pageable)
                    throws Exception {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getCurrentUser(token);
        Page<BlogComment> page =
                blogCommentRepository.findByBlogIdAndState(id, LiveDieState.LIVE, pageable);
        return ajax.setObj(page.map(new Converter<BlogComment, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(BlogComment source) {
                Map<String, Object> map = MapUtils.convert(source);
                User user = userRepository.findOne(source.userId);
                map.put("nickName", user.nickName);
                map.put("photo", user.photo);
                return map;
            }

        }));
    }


    @ResponseBody
    @RequestMapping(path = "comment_save", method = RequestMethod.POST)
    public AjaxResponse comment_save(HttpServletRequest request, String token, Long id, String text,
            HttpServletResponse response,
            @PageableDefault(sort = {"id"}, direction = Direction.DESC) Pageable pageable)
                    throws Exception {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getCurrentUser(token);
        BlogComment bc = new BlogComment();
        bc.blogId = id;
        bc.text = text;
        bc.userId = su.id;
        blogCommentRepository.save(bc);
        return ajax;
    }

    @Autowired
    private AccountGroupRepository accountGroupRepository;

    @Transactional
    @ResponseBody
    @RequestMapping(path = "verify_hh", method = RequestMethod.POST)
    public AjaxResponse verify_hh(HttpServletRequest request, String token, Long id,
            VerifyState state, HttpServletResponse response) throws Exception {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getCurrentUser(token);
        AccountGroupDetail agd = accountGroupDetailRepository.findByBlogId(id);
        if (agd.state == state) {
            return ajax;
        }
        if (state == VerifyState.TG) {
            accountGroupRepository.updatePayMoneyByUserIdAndGroupId(agd.userId, agd.groupId,
                    agd.money);
            String[] ids = StringUtils.strip(agd.userIds, ",").split(",");
            for (String userId : ids) {
                if (!StringUtils.isEmpty(userId)) {
                    accountGroupRepository.updateMoneyByUserIdAndGroupId(Long.valueOf(userId),
                            agd.groupId, agd.userIdsMoney);
                }
            }
        } else {
            if (agd.state == VerifyState.TG) {
                accountGroupRepository.updatePayMoneyByUserIdAndGroupId(agd.userId, agd.groupId,
                        -agd.money);
                String[] ids = StringUtils.strip(agd.userIds, ",").split(",");
                for (String userId : ids) {
                    if (!StringUtils.isEmpty(userId)) {
                        accountGroupRepository.updateMoneyByUserIdAndGroupId(Long.valueOf(userId),
                                agd.groupId, -agd.userIdsMoney);
                    }
                }
            }
        }
        agd.state = state;
        accountGroupDetailRepository.save(agd);
        return ajax;
    }
}
